package com.mars.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mars.common.base.UserContextInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * @author Mars
 */
@Component
public class CustomerMetaHandler implements MetaObjectHandler {
    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createTime";
    /**
     * 创建账号ID
     */
    private static final String CREATOR_BY = "createById";
    /**
     * 创建人名称
     */
    private static final String CREATOR_BY_NAME = "createByName";

    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "updateTime";
    /**
     * 更新账号ID
     */
    private static final String UPDATE_BY = "updateById";
    /**
     * 更新人名称
     */
    private static final String UPDATE_BY_NAME = "updateByName";


    /**
     * 新增数据执行
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        getUserInfo(metaObject, CREATOR_BY, CREATOR_BY_NAME, CREATE_TIME);


    }

    /**
     * 更新数据执行
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        getUserInfo(metaObject, UPDATE_BY, UPDATE_BY_NAME, UPDATE_TIME);

    }

    private void getUserInfo(MetaObject metaObject, String userIdField, String usernameField, String operateTimeFiled) {
        UserContextInfo userInfo = ContextUserInfoThreadHolder.get();
        if (!ObjectUtils.isEmpty(userInfo)) {
            Long userId = userInfo.getId();
            String userName = userInfo.getUserName();
            if (metaObject.hasGetter(userIdField)) {
                this.setFieldValByName(userIdField, userId, metaObject);
            }
            if (metaObject.hasGetter(usernameField)) {
                this.setFieldValByName(usernameField, userName, metaObject);
            }
        }

        if (metaObject.hasGetter(operateTimeFiled)) {
            this.setFieldValByName(operateTimeFiled, LocalDateTime.now(), metaObject);
        }
    }
}
